import { Injectable } from '@angular/core';
import { App } from 'ionic-angular';
import { HttpProvider } from '../http/http';
import { StorageProvider } from '../storage/storage';
import { Sha1Provider } from '../sha1/sha1';
import { UnitsProvider } from '../units/units';
import { DialogProvider } from '../dialog/dialog';
/*
  Generated class for the WechatProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
declare let wx: any;
//参数传递 -- 接到参数，最后跳转
//参数传递 -- ionic=%%%dsscc
//
@Injectable()
export class WechatProvider {

	public WX_CHATID = 'wxe81b1ff75733536d'; //微信模式
	public APP_SHARE_URL = 'http://kaleyun.kmaoxx.com';//微信分享路径

	constructor(
		public app: App,
		public http: HttpProvider,
		public storage: StorageProvider,
		public sha1: Sha1Provider,
		public units: UnitsProvider,
		public dialog: DialogProvider) {
		console.log('Hello WechatProvider Provider');
	}

	//登录
	public wechat_login() {
		//授权code
		let code = this.units.urlParams("code");
		let state = this.units.urlParams("state");
		if (code == undefined && state == undefined) {
			//检查机制
			this.loadSessionUser();
		} else {
			//用户回调
			this.wechat_code(code, state);
		}
	}

	//设定分享
	//title：标题
	//desc：描述
	//thumb：缩略图
	//data ：必须包含 page和传递的参数
	public wechat_share(params: any) {

		var title = params['title'] == undefined ? "快猫卡乐" : params['title'];
		var desc = params['desc'] == undefined ? "专业专注" : params['desc'];
		var link = params['data'] == undefined ? this.APP_SHARE_URL : this.APP_SHARE_URL + "/#/tabs/home/home&ionic=" + this.units.base64Encrypt(JSON.stringify(params['data']));
		var imgUrl = params['thumb'] == undefined ? this.APP_SHARE_URL + "/logo.png" : params['thumb'];

		//获取“分享到朋友圈”按钮点击状态及自定义分享内容接口
		wx.onMenuShareTimeline({
			title: title,
			desc: desc,
			link: link,
			imgUrl: imgUrl,
			success: function () {
				// 用户确认分享后执行的回调函数
			},
			cancel: function () {
				// 用户取消分享后执行的回调函数
			}
		});
		//获取“分享给朋友”按钮点击状态及自定义分享内容接口
		wx.onMenuShareAppMessage({
			title: title,
			desc: desc,
			link: link,
			imgUrl: imgUrl,
			success: function (res) {
				// 用户确认分享后执行的回调函数
			},
			cancel: function (res) {
				// 用户取消分享后执行的回调函数
			}
		});
		//获取“分享到QQ”按钮点击状态及自定义分享内容接口
		wx.onMenuShareQQ({
			title: title,
			desc: desc,
			link: link,
			imgUrl: imgUrl,
			success: function () {
				// 用户确认分享后执行的回调函数
			},
			cancel: function () {
				// 用户取消分享后执行的回调函数
			}
		});
		//获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口
		wx.onMenuShareWeibo({
			title: title,
			desc: desc,
			link: link,
			imgUrl: imgUrl,
			success: function () {
				// 用户确认分享后执行的回调函数
			},
			cancel: function () {
				// 用户取消分享后执行的回调函数
			}
		});
		//获取“分享到QQ空间”按钮点击状态及自定义分享内容接口
		wx.onMenuShareQZone({
			title: title,
			desc: desc,
			link: link,
			imgUrl: imgUrl,
			success: function () {
				// 用户确认分享后执行的回调函数
			},
			cancel: function () {
				// 用户取消分享后执行的回调函数
			}
		});
	}

	//微信初始化
	private wechat_init() {
		let that = this;
		let url = window.location.href.split('#')[0];
		this.wechat_sign(url).then(result => {
			// 配置参数
			let config = {
				debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				appId: result['appid'], // 必填，公众号的唯一标识
				timestamp: result['timestamp'], // 必填，生成签名的时间戳
				nonceStr: result['nonceStr'], // 必填，生成签名的随机串
				signature: result['signature'], // 必填，签名，见附录1
				jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem',
					'showAllNonBaseMenuItem', 'translateVoice', 'startRecord', 'stopRecord', 'onRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'uploadVoice', 'downloadVoice',
					'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'closeWindow',
					'scanQRCode', 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard'
				]
			}; // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
			// 通过config接口注入权限验证配置
			wx.config(config);
			// 通过ready接口处理成功验证
			wx.ready(function () {
				//已经准备完毕
				// config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，
				// 所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。
				// 对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
				let params = { "title": '快猫卡乐', "desc": '快猫卡乐,专业专注!' };
				that.wechat_share(params);
			});
			// 通过error接口处理失败验证
			wx.error(function (res) {
				// config信息验证失败会执行error函数，如签名过期导致验证失败，
				// 具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
			});
		});
	}

	//初始化(授权回调才会调用)
	private wechat_code(code: any, state: any) {
		//进行微信登录
		let that = this;
		if (code != undefined && state == "wechat") {
			//进行用户登陆
			that.wechat_auth(code).then(success => {
				//恢复网址
				that.wechat_page_go();
				//初始化微信组件(页面刷新)
				this.wechat_init();
			}, error => {
				that.dialog.showAlert("提示", "微信登陆失败");
			});
		} else {
			//初始化微信组件(页面刷新)
			this.wechat_init();
		}
	}

	//用户登录(微信公众号)
	private wechat_auth(code) {
		return new Promise((success, error) => {
			//授权请求
			this.http.postJson('wechat', 'codeauth', {
				'code': code
			}, false).then(res => {
				//登录成功
				this.storage.saveStorage('user', { 'user_id': res['data']['id'] }).then(result => {
					if (success)
						success();
				});
			}, fail => {
				if (error)
					error();
			});
		});
	}

	//用户授权(微信公众号)
	private wechat_snsapi_userinfo(state) {
		//未登录进行登录
		let url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
			this.WX_CHATID + '&redirect_uri=' + encodeURIComponent(window.location.href) +
			'&response_type=code&scope=snsapi_userinfo&state=' + state + '#wechat_redirect';
		return url
	}

	// 生成签名的随机串
	private wechat_noncestr() {
		return Math.random().toString(36).substr(2, 15);
	};

	// 生成签名的时间戳
	private wechat_timestamp() {
		let timestamp = new Date().getTime() / 1000;
		return parseInt(timestamp.toString()).toString();
	};

	// 排序整理数据
	private wechat_raw(args) {
		let keys = Object.keys(args);
		keys = keys.sort();
		let newArgs = {};
		keys.forEach(function (key) {
			newArgs[key.toLowerCase()] = args[key];
		});
		let result = '';
		for (let k in newArgs) {
			if (newArgs.hasOwnProperty(k)) {
				result += '&' + k + '=' + newArgs[k];
			}
		}
		result = result.substr(1);
		return result;
	};

	//签名校验
	private wechat_sign(url: any) {
		return new Promise((success) => {
			//请求
			this.http.postJson('wechat', 'jsticket', {}, false).then(res => {
				// 参数构成
				let ret = {
					jsapi_ticket: res['data'],
					nonceStr: this.wechat_noncestr(),
					timestamp: this.wechat_timestamp(),
					url: url
				};
				// 签名做成
				let result = this.wechat_raw(ret);
				ret['signature'] = this.sha1.hash(result);
				ret['appid'] = this.WX_CHATID;
				// 删除数据
				delete ret.jsapi_ticket;
				delete ret.url;
				// 函数回调
				success(ret);
			}, fail => {

			});
		});
	}

	//恢复网址
	private wechat_page_go() {
		let that = this;
		this.storage.getStorage('ionic_data').then((val) => {
			if (val) {
				let json = this.units.base64Decrypt(val);
				let data = JSON.parse(json);//转为对象
				let page = data['page'];
				delete data['page'];
				this.storage.removeStorage('ionic_data').then(success => {
					//页面跳转
					that.app.viewDidLoad.emit();
					that.app.viewDidEnter.emit();
					var nav = that.app.getActiveNav();
					nav.push(page, data);
				});
			} else {
				//页面重新加载
				that.app.viewDidLoad.emit();
				that.app.viewDidEnter.emit();

			}
		});
	}

	//由session缓存,然后存入系统内存
	private loadSessionUser() {
		//检查用户是否已经登录
		this.storage.getStorage('user').then(val => {
			//是否登录
			if (val == undefined || val['user_id'] == undefined) {
				//执行授权登录
				var snsapiUrl = this.wechat_snsapi_userinfo("wechat");
				//获取分享出去的参数 ionic 
				let ionic_data = this.units.urlParams("ionic");
				//保存数据
				if (ionic_data) {
					this.storage.saveStorage('ionic_data', ionic_data).then(success => {
						//默认静默授权
						setTimeout("javascript:location.href='" + snsapiUrl + "'", 100);
					});
				} else {
					setTimeout("javascript:location.href='" + snsapiUrl + "'", 100);
				}
			} else {
				//初始化微信组件(页面刷新)
				this.wechat_init();
			}
		});
	}

}